package com.martin.ads.vrlib.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLES20;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Ads on 2016/11/8.
 */
public class BitmapUtils {


    public static void sendImage(int width, int height, Context context) {
        final IntBuffer pixelBuffer = IntBuffer.allocate(width * height);

        //depends on the resolution of screen, about 20-50ms (1280x720)
        long start = System.nanoTime();
        GLES20.glReadPixels(0, 0, width, height, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE,
                pixelBuffer);
        long end = System.nanoTime();

        Log.d("TryOpenGL", "glReadPixels time: " + (end - start) / 1000000 + " ms");

        //about 700-4000ms(png) 200-1000ms(jpeg)
        //use jpeg instead of png to save time
        //it will consume large memory and may take a long time, depends on the phone
        new SaveBitmapTask(pixelBuffer, width, height, context).execute();
    }

    static class SaveBitmapTask extends AsyncTask<Void, Integer, Boolean> {
        long start;

        IntBuffer rgbaBuf;
        int width, height;
        Context context;

        String filePath;

        public SaveBitmapTask(IntBuffer rgbaBuf, int width, int height, Context context) {
            this.rgbaBuf = rgbaBuf;
            this.width = width;
            this.height = height;
            this.context = context;
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
            File sdRoot = Environment.getExternalStorageDirectory();
            String dir = "/Pano360Screenshots/";
            File mkDir = new File(sdRoot, dir);
            if (!mkDir.exists())
                mkDir.mkdir();
            String filename = "/PanoScreenShot_" + width + "_" + height + "_" + simpleDateFormat.format(new Date()) + ".jpg";
            filePath = mkDir.getAbsolutePath() + filename;
        }

        @Override
        protected void onPreExecute() {
            start = System.nanoTime();
            super.onPreExecute();
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            saveRgb2Bitmap(rgbaBuf, filePath, width, height);
            return true;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            Log.d("TryOpenGL", "saveBitmap time: " + (System.nanoTime() - start) / 1000000 + " ms");
            Toast.makeText(context, "ScreenShot is saved to " + filePath, Toast.LENGTH_LONG).show();
            super.onPostExecute(aBoolean);
        }
    }

    public static void saveRgb2Bitmap(IntBuffer buf, String filePath, int width, int height) {
        final int[] pixelMirroredArray = new int[width * height];
        Log.d("TryOpenGL", "Creating " + filePath);
        BufferedOutputStream bos = null;
        try {
            int[] pixelArray = buf.array();
            // rotate 180 deg with x axis because y is reversed
            for (int i = 0; i < height; i++) {
                for (int j = 0; j < width; j++) {
                    pixelMirroredArray[(height - i - 1) * width + j] = pixelArray[i * width + j];
                }
            }
            bos = new BufferedOutputStream(new FileOutputStream(filePath));
            Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            bmp.copyPixelsFromBuffer(IntBuffer.wrap(pixelMirroredArray));
            bmp.compress(Bitmap.CompressFormat.JPEG, 90, bos);
            bmp.recycle();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public static Bitmap loadBitmapFromAssets(Context context, String filePath) {
        InputStream inputStream = null;
        try {
            inputStream = context.getResources().getAssets().open(filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (inputStream == null) return null;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inScaled = false;
        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
        return bitmap;
    }

    public static Bitmap loadBitmapFromRaw(Context context, int resourceId) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inScaled = false;
        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resourceId, options);
        return bitmap;
    }

    /**
     * 将bgra转换成rgba
     * @param data
     */
    public static float[] convertByteToColorFloat(byte[] data){
        int size;
        if (data == null || (size = data.length) == 0){
            return null;
        }

        int arg = 0;
//        if (size % 3 != 0){
//            arg = 1;
//        }

        // 一般情况下data数组的长度应该是3的倍数，这里做个兼容，多余的RGB数据用黑色0XFF000000填充
        float color[] = new float[size / 4];
        int a, r, g, b;

        if (arg == 0){
            for(int i = 0; i < color.length; ++i){
                b = 0xff & (data[i * 4]);
                g = 0xff & (data[i * 4 + 1]);
                r = 0xff & (data[i * 4 + 2]);
                a = 0xff & (data[i * 4 + 3]);
                // 获取RGB分量值通过按位或生成int的像素值
                color[i] = (r<<16) | (g<<8) | (b) | (a<<24);
            }
        }
        return color;
    }


    /**
     * 将bgra转换成rgba
     * @param data
     */
    public static int[] convertByteToColor(byte[] data){
        int size;
        if (data == null || (size = data.length) == 0){
            return null;
        }

        int arg = 0;
        /*if (size % 3 != 0){
            arg = 1;
        }*/

        // 一般情况下data数组的长度应该是3的倍数，这里做个兼容，多余的RGB数据用黑色0XFF000000填充
        int color[] = new int[size / 4];
        int a, r, g, b;

        if (arg == 0){
            for(int i = 0; i < color.length; ++i){
                b = 0xff & (data[i * 4]);
                g = 0xff & (data[i * 4 + 1]);
                r = 0xff & (data[i * 4 + 2]);
                a = 0xff & (data[i * 4 + 3]);
                // 获取RGB分量值通过按位或生成int的像素值
                color[i] = (r<<16) | (g<<8) | (b) | (a<<24);
            }
        }
        return color;
    }

    public static byte[] getPixelsRGBA(Bitmap image) {
        int bytes = image.getByteCount();

        ByteBuffer buffer = ByteBuffer.allocate(bytes); // Create a new buffer
        image.copyPixelsToBuffer(buffer); // Move the byte data to the buffer

        byte[] temp = buffer.array(); // Get the underlying array containing the data.
        return temp;
    }


    public static byte[] getPixelsBGRA(Bitmap image) {
        // calculate how many bytes our image consists of
        int bytes = image.getByteCount();

        ByteBuffer buffer = ByteBuffer.allocate(bytes); // Create a new buffer
        image.copyPixelsToBuffer(buffer); // Move the byte data to the buffer

        byte[] temp = buffer.array(); // Get the underlying array containing the data.

        byte[] pixels = new byte[temp.length]; // Allocate for BGRA

        // Copy pixels into place
        for (int i = 0; i < (temp.length / 4); i++) {

            pixels[i * 4] = temp[i * 4 + 2];        //B
            pixels[i * 4 + 1] = temp[i * 4 + 1];//G
            pixels[i * 4 + 2] = temp[i * 4];       //R
            pixels[i * 4 + 3] = temp[i * 4 + 3];        //A

        }

        return pixels;
    }

    public static Bitmap rgb2Bitmap(int[] rgb, int imageWidth, int imageHeight) {
        Bitmap bm = Bitmap.createBitmap(rgb, imageWidth, imageHeight, Bitmap.Config.ARGB_8888);
        return bm;
    }


    //解码，yuv420sp转为RGB格式
    static public void decodeYUV420SP(int[] rgb, byte[] yuv420sp, int width,
                                      int height) {
        final int frameSize = width * height;

        for (int j = 0, yp = 0; j < height; j++) {
            int uvp = frameSize + (j >> 1) * width, u = 0, v = 0;
            for (int i = 0; i < width; i++, yp++) {
                int y = (0xff & ((int) yuv420sp[yp])) - 16;
                if (y < 0)
                    y = 0;
                if ((i & 1) == 0) {
                    v = (0xff & yuv420sp[uvp++]) - 128;
                    u = (0xff & yuv420sp[uvp++]) - 128;
                }

                int y1192 = 1192 * y;
                int r = (y1192 + 1634 * v);
                int g = (y1192 - 833 * v - 400 * u);
                int b = (y1192 + 2066 * u);

                if (r < 0)
                    r = 0;
                else if (r > 262143)
                    r = 262143;
                if (g < 0)
                    g = 0;
                else if (g > 262143)
                    g = 262143;
                if (b < 0)
                    b = 0;
                else if (b > 262143)
                    b = 262143;

                rgb[yp] = 0xff000000 | ((r << 6) & 0xff0000)
                        | ((g >> 2) & 0xff00) | ((b >> 10) & 0xff);
            }
        }
    }

}
